package com.utc.cards.table.jade.agent.gameAgent;

import jade.core.AID;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.utc.cards.common.jade.Mapper;
import com.utc.cards.model.HostModel;
import com.utc.cards.model.game.Info;
import com.utc.cards.model.game.InfoType;
import com.utc.cards.model.player.Hands;
import com.utc.cards.model.player.IPlayer;
import com.utc.cards.player.jade.agent.playerAgent.PlayerAgent;

public class GameSendCardBehaviour extends OneShotBehaviour
{

    private static final long serialVersionUID = -2214809689815293475L;
    private static Logger log = LoggerFactory.getLogger(PlayerAgent.class);

    private GameAgent agent;
    private InfoType infoType;
    private Hands hands;
    private IPlayer player;
    private HostModel model;

    public GameSendCardBehaviour(GameAgent gameAgent, InfoType infoType, Hands hands, IPlayer player)
    {
        super(gameAgent);
        this.agent = gameAgent;
        this.infoType = infoType;
        this.hands = hands;
        this.player = player;
        this.model = agent.getModel();
    }

    @Override
    public void action()
    {
        log.debug("Sending cards to {}", player.getName());
        AID playerAID = model.getPlayersMap().get(player.getName());
        if (playerAID != null)
        {
            ACLMessage message = new ACLMessage(ACLMessage.INFORM);
            message.setConversationId("info");
            message.addReceiver(playerAID);
            String json = null;
            try
            {
                json = Mapper.getObjectMapper().writeValueAsString(hands);
            }
            catch (JsonProcessingException e)
            {
                log.error("Error while mapping Map<String,Deck> to String");
                e.printStackTrace();
            }
            if (json != null)
            {
                Info info = new Info(infoType, json);
                try
                {
                    message.setContent(Mapper.getObjectMapper().writeValueAsString(info));
                    agent.send(message);
                }
                catch (JsonProcessingException e)
                {
                    log.error("Error while mapping Info to String");
                    e.printStackTrace();
                }
            }
        }

    }

}
